package com.termux.zerocore.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.xh_lib.utils.UUtils;
import com.google.gson.Gson;
import com.termux.R;
import com.termux.app.TermuxActivity;
import com.termux.app.TermuxInstaller;
import com.termux.zerocore.activity.adapter.CreateSystemAdapter;
import com.termux.zerocore.bean.CreateSystemBean;
import com.termux.zerocore.bean.ReadSystemBean;
import com.termux.zerocore.dialog.MyDialog;
import com.termux.zerocore.shell.ExeCommand;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SwitchActivity extends AppCompatActivity implements View.OnClickListener {

    private ListView list;
    private ImageView create_img;
    private File mFile = new File("/data/data/com.termux/");
    private File mFileTEMP = new File("/data/data/com.termux/temp");
    private File mDefFile = new File("/data/data/com.termux/files/xinhao_system.infoJson");
    private File mFileHomeStatic = new File("/data/data/com.termux/busybox_static");
    private File mFileHome = new File("/data/data/com.termux/busybox");
    private CreateSystemAdapter createSystemAdapter;
    private ExecutorService executorService = Executors.newFixedThreadPool(2); // 线程池管理后台任务
    private Handler mainHandler = new Handler(Looper.getMainLooper()); // 主线程 Handler
    private MyDialog myDialog;

    
    
    private static SwitchActivity instance;
    private List<ReadSystemBean> globalMList;
    private int globalPosition;

    
    public SwitchActivity() {} // 私有构造

  public static SwitchActivity getInstance() {
    if (instance == null) {
        synchronized (SwitchActivity.class) {
            if (instance == null) {
                instance = new SwitchActivity();
            }
        }
    }
    return instance;
}
//    public static synchronized SwitchActivity getInstance() {
//        if (instance == null) {
//            instance = new SwitchActivity();
//        }
//        return instance;
//    }

    // Getter/Setter 方法
    public void setGlobalMList(List<ReadSystemBean> list) {
        this.globalMList = list;
    }
    public List<ReadSystemBean> getGlobalMList() {
        return globalMList;
    }
    public void setGlobalPosition(int position) {
        this.globalPosition = position;
    }
    public int getGlobalPosition() {
        return globalPosition;
    }
    
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_switch);

        list = findViewById(R.id.list_switch);
        create_img = findViewById(R.id.create_img);
        create_img.setOnClickListener(this);

        clickList();
        isIofo();
        readFileAsync(); // 修正为异步读取文件
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissMyDialog(); // 防止对话框泄漏
        executorService.shutdown(); // 关闭线程池
    }
@Override
protected void onResume() {
    super.onResume();
    executorService.execute(() -> {
        try {
            // 检查文件是否存在，不存在则解压
            if (!mFileHome.exists() || !mFileHomeStatic.exists()) {
                String cpu = TermuxInstaller.determineTermuxArchName();
                switch (cpu) {
                    case "aarch64":
                        writerFile("zero_busybox/busybox_arm64", mFileHome, 1024);
                      //  writerFile("arm_64/busybox_static", mFileHomeStatic, 1024);
                        break;
                    case "arm":
                        writerFile("zero_busybox/busybox_arm", mFileHome, 1024);
                        break;
                    case "x86_64":
                        writerFile("zero_busybox/busybox_x86_64", mFileHome, 1024);
                        break;
                }
//               switch (cpu) {
//                          case "aarch64":
//                                writerFile("zipcommand/busybox_arm64.7z", mFileHome);
//                          break;
//                          case "arm":
//                                writerFile("zipcommand/busybox_arm.7z", mFileHome);
//                          break;
//                          case "x86_64":
//                                // Handle x86_64 if there's a corresponding .7z file
//                     break;
//                              }
                Runtime.getRuntime().exec("chmod 777 " + mFileHome.getAbsolutePath());
                Runtime.getRuntime().exec("chmod 777 " + mFileHomeStatic.getAbsolutePath());
            }
        } catch (Exception e) {
            Log.e("XINHAO_HAN", "onResume error: ", e);
        }
    });
}

private void writerFile(String assetName, File targetFile) {
    if (assetName.endsWith(".7z")) {
        handleSevenZipExtraction(assetName, targetFile);
    } else {
        try (InputStream input = getAssets().open(assetName);
             FileOutputStream output = new FileOutputStream(targetFile)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = input.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }
            output.flush();
        } catch (IOException e) {
            Log.e("XINHAO_HAN_FILE", "writerFile error: ", e);
            mainHandler.post(() -> Toast.makeText(this, "解压安装文件失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
        }
    }
}

private void handleSevenZipExtraction(String assetName, File targetFile) {
    File tempSevenZipFile = new File(getCacheDir(), assetName);
    try (InputStream input = getAssets().open(assetName);
         FileOutputStream output = new FileOutputStream(tempSevenZipFile)) {
        byte[] buffer = new byte[1024];
        int len;
        while ((len = input.read(buffer)) != -1) {
            output.write(buffer, 0, len);
        }
        output.flush();
    } catch (IOException e) {
        Log.e("XINHAO_HAN_FILE", "Error copying .7z file: ", e);
        mainHandler.post(() -> Toast.makeText(this, "Error copying .7z file: " + e.getMessage(), Toast.LENGTH_SHORT).show());
        return;
    }

    String sevenZipPath = findSevenZipPath();
    if (sevenZipPath == null) {
        mainHandler.post(() -> Toast.makeText(this, "7z is not installed. Please install p7zip package.", Toast.LENGTH_LONG).show());
        return;
    }

    File tempExtractDir = new File(getCacheDir(), "extract");
    tempExtractDir.mkdirs();
    String extractCommand = sevenZipPath + " x " + tempSevenZipFile.getPath() + " -o" + tempExtractDir.getPath();
    try {
        Process process = Runtime.getRuntime().exec(extractCommand);
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            Log.e("XINHAO_HAN_FILE", "Error extracting .7z file: exit code " + exitCode);
            mainHandler.post(() -> Toast.makeText(this, "Error extracting .7z file.", Toast.LENGTH_SHORT).show());
            return;
        }
    } catch (IOException | InterruptedException e) {
        Log.e("XINHAO_HAN_FILE", "Error executing extraction command: ", e);
        mainHandler.post(() -> Toast.makeText(this, "Error extracting .7z file: " + e.getMessage(), Toast.LENGTH_SHORT).show());
        return;
    }

    File extractedFile = new File(tempExtractDir, "busybox");
    if (extractedFile.exists()) {
        try {
            copyFile(extractedFile, targetFile);
        } catch (IOException e) {
            Log.e("XINHAO_HAN_FILE", "Error copying extracted file: ", e);
            mainHandler.post(() -> Toast.makeText(this, "Error copying extracted file: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            return;
        }
    } else {
        Log.e("XINHAO_HAN_FILE", "Extracted file not found: busybox");
        mainHandler.post(() -> Toast.makeText(this, "Extracted file not found.", Toast.LENGTH_SHORT).show());
        return;
    }

    tempSevenZipFile.delete();
    for (File file : tempExtractDir.listFiles()) {
        file.delete();
    }
    tempExtractDir.delete();
}
private void copyFile(File source, File destination) throws IOException {
    try (FileInputStream inputStream = new FileInputStream(source);
         FileOutputStream outputStream = new FileOutputStream(destination)) {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        Log.d("XINHAO_HAN_FILE", "Successfully copied file from " + source.getPath() + " to " + destination.getPath());
    } catch (IOException e) {
        Log.e("XINHAO_HAN_FILE", "Error copying file: ", e);
        throw new IOException("Failed to copy file: " + e.getMessage(), e);
    }
}
private String findSevenZipPath() {
    try {
        Process process = Runtime.getRuntime().exec("which 7z");
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String path = reader.readLine();
        if (path != null && !path.isEmpty()) {
            return path;
        }
    } catch (IOException e) {
        Log.e("XINHAO_HAN_FILE", "Error finding 7z path: ", e);
    }
    return null;
}


    private void dismissMyDialog() {
        if (myDialog != null && myDialog.isShowing()) {
            myDialog.dismiss();
            myDialog = null;
        }
    }

    private void isIofo() {
        if (!mDefFile.exists()) {
            executorService.execute(() -> {
                try {
                    mDefFile.createNewFile();
                    CreateSystemBean createSystemBean = new CreateSystemBean();
                    createSystemBean.systemName = UUtils.getString(R.string.无名称系统);
                    createSystemBean.dir = "/data/data/com.termux/files";
                    String s = new Gson().toJson(createSystemBean);
                    writeToFile(mDefFile, s);
                } catch (IOException e) {
                    Log.e("XINHAO_HAN", "isIofo error: ", e);
                }
            });
        }
    }




    private void clickList() {
        list.setOnItemClickListener((parent, view, position, id) -> {
            List<ReadSystemBean> mList = createSystemAdapter.mList;
            String[] options = {UUtils.getString(R.string.删除), UUtils.getString(R.string.切换)};
         
      //  this.globalMList = mList;
      //  this.globalPosition = position;
        SwitchActivity.getInstance().setGlobalMList(mList);
         SwitchActivity.getInstance().setGlobalPosition(position);

            new AlertDialog.Builder(this)
                    .setTitle(UUtils.getString(R.string.删除完成_需要重进才能刷新))
                    .setItems(options, (dialog, which) -> {
                        if (which == 0) {
                            confirmDeleteSystem(mList, position);
                        } else {
                            switchSystem(mList, position);
                        }
                    }).show();
        });
    }

    private void confirmDeleteSystem(List<ReadSystemBean> mList, int position) {
        if (mList.get(position).dir.equals("/data/data/com.termux/files")) {
            Toast.makeText(this, "你不能删除主系统", Toast.LENGTH_SHORT).show();
            return;
        }

        new AlertDialog.Builder(this)
                .setTitle("你确定要删除吗")
                .setMessage("请确保你的SD卡权限未被获取!\n否则可能会清空SD卡上的所有内容!\n你确定要删除吗?\n删除后数据不可恢复!!!!!!")
                .setNegativeButton("我确定", (dialog, which) -> deleteSystemAsync(mList, position))
                .setPositiveButton("我不删除", (dialog, which) -> Toast.makeText(this, "操作忽略", Toast.LENGTH_SHORT).show())
                .setNeutralButton("别删除", (dialog, which) -> Toast.makeText(this, "操作忽略", Toast.LENGTH_SHORT).show())
                .show();
    }

    private void deleteSystemAsync(List<ReadSystemBean> mList, int position) {
        myDialog = new MyDialog(this);
        myDialog.show();
        myDialog.getDialog_title().setText("正在删除,请耐心等待...");
        myDialog.getDialog_pro().setText("时间长短由系统大小决定");

        executorService.execute(() -> {
            String dir = mList.get(position).dir;
            Log.e("XINHAO_HAN", "删除系统: " + dir);
            try {
                String cpu = TermuxInstaller.determineTermuxArchName();
                switch (cpu) {
                    case "aarch64":
                        writerFile("zero_busybox/busybox_arm64", mFileHome, 1024);
                       // writerFile("arm_64/busybox_static", mFileHomeStatic, 1024);
                        break;
                    case "arm":
                        writerFile("zero_busybox/busybox_arm", mFileHome, 1024);
                        break;
                    case "x86_64":
                        writerFile("zero_busybox/busybox_x86_64", mFileHome, 1024);
                        break;
                }
                Runtime.getRuntime().exec("chmod 777 " + mFileHome.getAbsolutePath());
                Runtime.getRuntime().exec("chmod 777 " + mFileHomeStatic.getAbsolutePath());

                ExeCommand cmd = new ExeCommand(false).run(mFileHome.getAbsolutePath() + " rm -rf " + dir, 60000, false);
                while (cmd.isRunning()) {
                    Thread.sleep(5);
                    Log.e("XINHAO_HAN", "run: " + cmd.getResult());
                }

                mainHandler.post(() -> {
                    File file = new File(dir);
                    if (file.exists()) {
                        Toast.makeText(this, "正在清除系统残留文件", Toast.LENGTH_SHORT).show();
                        TermuxActivity.mTerminalView.sendTextToTerminal("chmod 777 -R " + dir + " && rm -rf " + dir + " \n");
                    } else {
                        Toast.makeText(this, "删除成功!", Toast.LENGTH_SHORT).show();
                    }
                    dismissMyDialog();
                    finish();
                });
            } catch (Exception e) {
                Log.e("XINHAO_HAN", "delete error: ", e);
                mainHandler.post(() -> {
                    Toast.makeText(this, "删除失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    dismissMyDialog();
                });
            }
        });
    }

    
    private void switchSystem(List<ReadSystemBean> mList, int position) {
    executorService.execute(() -> {
        try {
            // Read original mDefFile before any changes
            String json = readFileContent(mDefFile);
            CreateSystemBean currentSystem = new Gson().fromJson(json, CreateSystemBean.class);

            ReadSystemBean targetSystem = mList.get(position);

            // Perform directory swaps
            File targetDir = new File(targetSystem.dir);
            File currentDir = new File(currentSystem.dir);
            File tempDir = new File(getCacheDir(), "temp");

            // Swap directories
            targetDir.renameTo(tempDir);
            currentDir.renameTo(targetDir);
            tempDir.renameTo(currentDir);

            // Now, currentDir has what was in targetDir
            // targetDir has what was in currentDir

            // Update JSON files correctly
            // Read current_json which now has targetSystem’s JSON
            File currentJson = new File(currentDir, "xinhao_system.infoJson");
            String targetSystemJson = readFileContent(currentJson);
            CreateSystemBean targetSystemBean = new Gson().fromJson(targetSystemJson, CreateSystemBean.class);

            // Update its dir to currentDir path
            targetSystemBean.dir = currentDir.getPath();

            // Write back to current_json
            writeToFile(currentJson, new Gson().toJson(targetSystemBean));

            // Read targetJson which now has original currentSystem’s JSON
            File targetJson = new File(targetDir, "xinhao_system.infoJson");
            String originalCurrentSystemJson = readFileContent(targetJson);
            CreateSystemBean originalCurrentSystemBean = new Gson().fromJson(originalCurrentSystemJson, CreateSystemBean.class);

            // Update its dir to targetDir path
            originalCurrentSystemBean.dir = targetDir.getPath();

            // Write back to targetJson
            writeToFile(targetJson, new Gson().toJson(originalCurrentSystemBean));

            // Update UI
            mainHandler.post(() -> {
                setAllFalse(mList);
                mList.get(position).isCkeck = true;
                createSystemAdapter.notifyDataSetChanged();
                showSwitchSuccessDialog();
            });
        } catch (Exception e) {
            mainHandler.post(() -> Toast.makeText(this, "切换失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
        }
    });
}

    
    //安全的重启com.termux.app.TermuxActivity
    private void restartTermuxActivity() {
    try {
        // 创建 Intent 以重新启动 TermuxActivity
        Intent restartIntent = new Intent(this, TermuxActivity.class);
        restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        
        // 保存必要的状态（如果需要）
        // 例如，可以通过 Intent 传递参数告知 TermuxActivity 是重启后的状态
        restartIntent.putExtra("RESTARTED", true);

        // 结束当前进程并启动新的 Activity
        finishAffinity(); // 关闭当前应用的所有 Activity
        startActivity(restartIntent);
        
        // 确保进程完全退出
        System.exit(0);
    } catch (Exception e) {
        Log.e("XINHAO_HAN", "Failed to restart TermuxActivity: ", e);
        Toast.makeText(this, "重启失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}
    
    private void showSwitchSuccessDialog() {
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setCancelable(false)
                .setMessage("切换成功!\n需要完全退出重启APP才能生效\n需要重启吗\n请手动重启APP")
                .setNegativeButton("需要", (dialog, which) -> {
                
               // switchSystem(globalMList, globalPosition);
                Toast.makeText(this, "请手动退出APP", Toast.LENGTH_SHORT).show();
                finish();
                restartTermuxActivity();
                
                })
                .setPositiveButton("不需要", (dialog, which) -> {
                    Toast.makeText(this, "设置已生效!请重启APP", Toast.LENGTH_SHORT).show();
                    finish();
                })
                .show();
    }

    private void setAllFalse(List<ReadSystemBean> mList) {
        for (ReadSystemBean bean : mList) {
            bean.isCkeck = false;
        }
    }

    private void readFileAsync() {
        executorService.execute(() -> {
            File[] files = mFile.listFiles();
            ArrayList<ReadSystemBean> arrayList = new ArrayList<>();
            if (files != null) {
                for (File file : files) {
                    if (file.getName().startsWith("files")) {
                        ReadSystemBean bean = new ReadSystemBean();
                        bean.dir = file.getAbsolutePath();
                        String name = readInfo(file.getAbsolutePath());
                        if (name == null) {
                            new File(file, "/xinhao_system.infoJson").delete();
                            mainHandler.post(() -> {
                                Toast.makeText(this, "配置文件已损坏，请重新创建", Toast.LENGTH_SHORT).show();
                                finish();
                            });
                            return;
                        }
                        bean.name = name;
                        arrayList.add(bean);
                    }
                }
            }
            mainHandler.post(() -> setAdapter(arrayList));
        });
    }

    private void setAdapter(ArrayList<ReadSystemBean> arrayList) {
        createSystemAdapter = new CreateSystemAdapter(arrayList, this);
        list.setAdapter(createSystemAdapter);
        setDefSystemAsync(arrayList);
    }

    private void setDefSystemAsync(ArrayList<ReadSystemBean> arrayList) {
        executorService.execute(() -> {
            try {
                String json = readFileContent(mDefFile);
                CreateSystemBean defaultSystem = new Gson().fromJson(json, CreateSystemBean.class);
                if (defaultSystem == null) {
                    defaultSystem = new CreateSystemBean();
                    defaultSystem.dir = "/data/data/com.termux/files/";
                    defaultSystem.systemName = "默认系统";
                }
                for (ReadSystemBean bean : arrayList) {
                    if (bean.name.equals(defaultSystem.systemName)) {
                        bean.isCkeck = true;
                        break;
                    }
                }
                mainHandler.post(() -> createSystemAdapter.notifyDataSetChanged());
            } catch (Exception e) {
                mainHandler.post(() -> Toast.makeText(this, "读取默认系统失败", Toast.LENGTH_SHORT).show());
            }
        });
    }

    private String readInfo(String path) {
        try {
            String json = readFileContent(new File(path, "/xinhao_system.infoJson"));
            CreateSystemBean bean = new Gson().fromJson(json, CreateSystemBean.class);
            return bean != null ? bean.systemName : "损坏的系统";
        } catch (Exception e) {
            Log.e("XINHAO_HAN", "readInfo error: ", e);
            return "默认系统";
        }
    }

    private String readFileContent(File file) throws IOException {
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        }
        return content.toString();
    }

    private void writeToFile(File file, String content) throws IOException {
        try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file)))) {
            writer.print(content);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.create_img) {
            createSystemDialog();
        }
    }

    private void createSystemDialog() {
        final EditText et = new EditText(this);
        new AlertDialog.Builder(this)
                .setTitle("请输入新的Linux名称")
                .setIcon(R.mipmap.linux_new_ico)
                .setView(et)
                .setPositiveButton("确定", (dialog, which) -> createSystemAsync(et.getText().toString()))
                .setNegativeButton("取消", null)
                .show();
    }

    private void createSystemAsync(String name) {
        executorService.execute(() -> {
            File[] files = mFile.listFiles();
            File createFile;
            if (files == null || files.length <= 1) {
                createFile = new File(mFile, "files1");
            } else {
                ArrayList<Integer> indices = new ArrayList<>();
                for (File file : files) {
                    if (file.getName().startsWith("files")) {
                        String suffix = file.getName().substring(5);
                        indices.add(suffix.isEmpty() ? 0 : Integer.parseInt(suffix));
                    }
                }
                int maxI = indices.stream().max(Integer::compare).orElse(0);
                createFile = new File(mFile, "files" + (maxI + 1));
            }

            createFile.mkdirs();
            CreateSystemBean bean = new CreateSystemBean();
            bean.dir = createFile.getAbsolutePath();
            bean.systemName = name;
            String json = new Gson().toJson(bean);

            File fileInfo = new File(createFile, "/xinhao_system.infoJson");
            try {
                fileInfo.createNewFile();
                writeToFile(fileInfo, json);
                mainHandler.post(() -> {
                    readFileAsync();
                    Toast.makeText(this, "系统创建成功", Toast.LENGTH_SHORT).show();
                });
            } catch (IOException e) {
                mainHandler.post(() -> Toast.makeText(this, "系统创建失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }
        });
    }

    private void writerFile(String assetName, File targetFile, int bufferSize) {
        try (InputStream input = getAssets().open(assetName);
             FileOutputStream output = new FileOutputStream(targetFile)) {
            if (!targetFile.exists()) {
                targetFile.createNewFile();
            }
            byte[] buffer = new byte[bufferSize];
            int len;
            while ((len = input.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }
            output.flush();
        } catch (IOException e) {
            Log.e("XINHAO_HAN_FILE", "writerFile error: ", e);
            mainHandler.post(() -> Toast.makeText(this, "解压安装文件失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
        }
    }
}